// 注册页面功能
function initRegisterPage() {
    console.log('初始化注册页面');
    
    // 检查 Supabase 是否初始化
    if (!supabase) {
        console.error('Supabase 未初始化');
        const messageDiv = document.getElementById('message');
        if (messageDiv) {
            showMessage(messageDiv, '系统初始化失败，请刷新页面', 'error');
        }
        return;
    }
    
    // 获取DOM元素
    const messageDiv = document.getElementById('message');
    
    // 注册方式切换
    const emailTab = document.getElementById('reg-email-tab');
    const phoneTab = document.getElementById('reg-phone-tab');
    const emailForm = document.getElementById('email-reg-form');
    const phoneForm = document.getElementById('phone-reg-form');
    
    // 邮箱注册元素
    const emailInput = document.getElementById('reg-email');
    const passwordInput = document.getElementById('reg-password');
    const confirmPasswordInput = document.getElementById('confirm-password');
    const registerBtn = document.getElementById('register-btn');
    
    // 手机注册方式切换
    const phoneRegCodeTab = document.getElementById('phone-reg-code-tab');
    const phoneRegPasswordTab = document.getElementById('phone-reg-password-tab');
    const phoneCodeRegister = document.getElementById('phone-code-register');
    const phonePasswordRegister = document.getElementById('phone-password-register');
    
    // 手机验证码注册元素
    const phoneInput = document.getElementById('reg-phone');
    const verificationInput = document.getElementById('reg-verification-code');
    const sendCodeBtn = document.getElementById('reg-send-code-btn');
    const phoneCodeRegisterBtn = document.getElementById('phone-code-register-btn');
    
    // 手机密码注册元素
    const phoneRegNumber = document.getElementById('phone-reg-number');
    const phoneRegPassword = document.getElementById('phone-reg-password');
    const phoneRegConfirmPassword = document.getElementById('phone-reg-confirm-password');
    const phonePasswordRegisterBtn = document.getElementById('phone-password-register-btn');
    
    // 切换注册方式
    if (emailTab && phoneTab) {
        emailTab.addEventListener('click', () => {
            emailTab.classList.add('active');
            phoneTab.classList.remove('active');
            emailForm.classList.remove('hidden');
            phoneForm.classList.add('hidden');
        });
        
        phoneTab.addEventListener('click', () => {
            phoneTab.classList.add('active');
            emailTab.classList.remove('active');
            phoneForm.classList.remove('hidden');
            emailForm.classList.add('hidden');
        });
    }
    
    // 手机注册方式切换
    if (phoneRegCodeTab && phoneRegPasswordTab) {
        phoneRegCodeTab.addEventListener('click', () => {
            phoneRegCodeTab.classList.add('active');
            phoneRegPasswordTab.classList.remove('active');
            phoneCodeRegister.classList.remove('hidden');
            phonePasswordRegister.classList.add('hidden');
        });
        
        phoneRegPasswordTab.addEventListener('click', () => {
            phoneRegPasswordTab.classList.add('active');
            phoneRegCodeTab.classList.remove('active');
            phonePasswordRegister.classList.remove('hidden');
            phoneCodeRegister.classList.add('hidden');
        });
    }
    
    // 手机号输入格式化
    if (phoneInput) {
        phoneInput.addEventListener('input', (e) => {
            const formatted = formatPhoneNumber(e.target.value);
            if (formatted !== e.target.value) {
                e.target.value = formatted;
            }
        });
    }
    
    if (phoneRegNumber) {
        phoneRegNumber.addEventListener('input', (e) => {
            const formatted = formatPhoneNumber(e.target.value);
            if (formatted !== e.target.value) {
                e.target.value = formatted;
            }
        });
    }
    
    // 发送验证码
    if (sendCodeBtn) {
        sendCodeBtn.addEventListener('click', async (e) => {
            e.preventDefault();
            
            const phone = phoneInput ? phoneInput.value.replace(/\s+/g, '') : '';
            
            if (!validatePhone(phone)) {
                showMessage(messageDiv, '请输入有效的手机号码', 'error');
                return;
            }
            
            await sendVerificationCode(phone, sendCodeBtn);
        });
    }
    
    // 邮箱注册
    if (registerBtn) {
        registerBtn.addEventListener('click', (e) => {
            e.preventDefault();
            
            const email = emailInput ? emailInput.value.trim() : '';
            const password = passwordInput ? passwordInput.value : '';
            const confirmPassword = confirmPasswordInput ? confirmPasswordInput.value : '';
            
            if (!email || !password || !confirmPassword) {
                showMessage(messageDiv, '请填写所有字段', 'error');
                return;
            }
            
            if (!validateEmail(email)) {
                showMessage(messageDiv, '请输入有效的邮箱地址', 'error');
                return;
            }
            
            if (password !== confirmPassword) {
                showMessage(messageDiv, '两次输入的密码不一致', 'error');
                return;
            }
            
            if (password.length < 6) {
                showMessage(messageDiv, '密码长度至少为6位', 'error');
                return;
            }
            
            registerWithEmail(email, password);
        });
    }
    
    // 手机验证码注册
    if (phoneCodeRegisterBtn) {
        phoneCodeRegisterBtn.addEventListener('click', (e) => {
            e.preventDefault();
            
            const phone = phoneInput ? phoneInput.value.replace(/\s+/g, '') : '';
            const code = verificationInput ? verificationInput.value : '';
            
            if (!phone || !code) {
                showMessage(messageDiv, '请填写所有字段', 'error');
                return;
            }
            
            if (!validatePhone(phone)) {
                showMessage(messageDiv, '请输入有效的手机号码', 'error');
                return;
            }
            
            if (code.length !== 6) {
                showMessage(messageDiv, '请输入6位验证码', 'error');
                return;
            }
            
            registerWithPhoneCode(phone, code);
        });
    }
    
    // 手机密码注册
    if (phonePasswordRegisterBtn) {
        phonePasswordRegisterBtn.addEventListener('click', (e) => {
            e.preventDefault();
            
            const phone = phoneRegNumber ? phoneRegNumber.value.replace(/\s+/g, '') : '';
            const password = phoneRegPassword ? phoneRegPassword.value : '';
            const confirmPassword = phoneRegConfirmPassword ? phoneRegConfirmPassword.value : '';
            
            if (!phone || !password || !confirmPassword) {
                showMessage(messageDiv, '请填写所有字段', 'error');
                return;
            }
            
            if (!validatePhone(phone)) {
                showMessage(messageDiv, '请输入有效的手机号码', 'error');
                return;
            }
            
            if (password !== confirmPassword) {
                showMessage(messageDiv, '两次输入的密码不一致', 'error');
                return;
            }
            
            if (password.length < 6) {
                showMessage(messageDiv, '密码长度至少为6位', 'error');
                return;
            }
            
            registerWithPhonePassword(phone, password);
        });
    }
    
    // 发送验证码函数
    async function sendVerificationCode(phone, button) {
        try {
            setButtonLoading(button, true, '发送中...');
            hideMessage(messageDiv);
            
            const { data, error } = await supabase.auth.signInWithOtp({
                phone: `+86${phone}`,
                options: {
                    channel: 'sms'
                }
            });
            
            if (error) {
                throw error;
            }
            
            showMessage(messageDiv, '验证码已发送到您的手机', 'success');
            startCountdown(button);
            
        } catch (error) {
            console.error('发送验证码错误:', error);
            showMessage(messageDiv, '发送验证码失败: ' + error.message, 'error');
        } finally {
            setButtonLoading(button, false);
        }
    }
    
    // 邮箱注册函数
    async function registerWithEmail(email, password) {
        try {
            setButtonLoading(registerBtn, true);
            hideMessage(messageDiv);
            
            const { data, error } = await supabase.auth.signUp({
                email: email,
                password: password,
            });
            
            if (error) {
                throw error;
            }
            
            showMessage(messageDiv, '注册成功！请检查您的邮箱以确认账户。', 'success');
            
            // 清空表单
            if (emailInput) emailInput.value = '';
            if (passwordInput) passwordInput.value = '';
            if (confirmPasswordInput) confirmPasswordInput.value = '';
            
        } catch (error) {
            console.error('注册错误:', error);
            showMessage(messageDiv, '注册失败: ' + error.message, 'error');
        } finally {
            setButtonLoading(registerBtn, false);
        }
    }
    
    // 手机验证码注册函数
    async function registerWithPhoneCode(phone, code) {
        try {
            setButtonLoading(phoneCodeRegisterBtn, true);
            hideMessage(messageDiv);
            
            // 首先验证验证码
            const { data: verifyData, error: verifyError } = await supabase.auth.verifyOtp({
                phone: `+86${phone}`,
                token: code,
                type: 'sms'
            });
            
            if (verifyError) {
                throw verifyError;
            }
            
            showMessage(messageDiv, '手机验证码注册成功！', 'success');
            
            // 清空表单
            if (phoneInput) phoneInput.value = '';
            if (verificationInput) verificationInput.value = '';
            
        } catch (error) {
            console.error('手机验证码注册错误:', error);
            showMessage(messageDiv, '注册失败: ' + error.message, 'error');
        } finally {
            setButtonLoading(phoneCodeRegisterBtn, false);
        }
    }
    
    // 手机密码注册函数
    async function registerWithPhonePassword(phone, password) {
        try {
            setButtonLoading(phonePasswordRegisterBtn, true);
            hideMessage(messageDiv);
            
            // 使用手机号作为用户名注册
            const { data, error } = await supabase.auth.signUp({
                phone: `+86${phone}`,
                password: password,
            });
            
            if (error) {
                throw error;
            }
            
            showMessage(messageDiv, '手机密码注册成功！', 'success');
            
            // 清空表单
            if (phoneRegNumber) phoneRegNumber.value = '';
            if (phoneRegPassword) phoneRegPassword.value = '';
            if (phoneRegConfirmPassword) phoneRegConfirmPassword.value = '';
            
        } catch (error) {
            console.error('手机密码注册错误:', error);
            showMessage(messageDiv, '注册失败: ' + error.message, 'error');
        } finally {
            setButtonLoading(phonePasswordRegisterBtn, false);
        }
    }
}